﻿namespace iFinance.SqoDAL
{
    using System;
    using System.Windows;
    using iFinance.Infrastructure;
    using iFinance.Infrastructure.Events;
    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Unity;
    using Sqo;

    /// <summary>
    /// Siaqodb系统数据库操作帮助类，操作用户无关的数据库
    /// </summary>
    public class SystemSqoHelper
    {
        #region 单例

        static SystemSqoHelper()
        {
            Instance = new SystemSqoHelper();
        }

        private SystemSqoHelper()
        {
            if (Application.Current.IsRunningOutOfBrowser && Application.Current.HasElevatedPermissions)
            {
                //use MyDocuments folder on client machine to store data
                DBContext = new Siaqodb(DataBaseName, Environment.SpecialFolder.MyDocuments);
            }
            else
            {
                //use IsolatedStorage to store data
                DBContext = new Siaqodb(DataBaseName);
            }
            //登录成功之后按照登录的用户初始化用户独立的数据库
            UnityHelper.Container.Resolve<IEventAggregator>().GetEvent<LoginSuccessEvent>().Subscribe(InitDataContext);           
        }

        public static SystemSqoHelper Instance { get; set; }

        #endregion

        #region 属性

        public const string DataBaseName = "iFinance";

        /// <summary>
        /// 数据库上下文实例
        /// </summary>
        public Siaqodb DBContext { get; set; }

        #endregion

        #region 方法

        /// <summary>
        /// 初始化数据库上下文实例
        /// </summary>
        /// <param name="userID"></param>
        public void InitDataContext(string userID)
        {
            if (Application.Current.IsRunningOutOfBrowser && Application.Current.HasElevatedPermissions)
            {
                //use MyDocuments folder on client machine to store data
                IndividualSqoHelper.Instance.DBContext = new Siaqodb(DataBaseName + "/" + userID, Environment.SpecialFolder.MyDocuments);
            }
            else
            {
                //use IsolatedStorage to store data
                IndividualSqoHelper.Instance.DBContext = new Siaqodb(DataBaseName + "/" + userID);
            }
        }

        /// <summary>
        /// 通用插入方法
        /// </summary>
        /// <param name="obj"></param>
        public bool Insert(object obj)
        {
            bool result = false;
            try
            {
                DBContext.StoreObject(obj);
                DBContext.Flush();
                result = true;
            }
            finally { }
            return result;
        }

        #endregion
    }
}
